package com.gzgy.ustore.api.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AreaUtil {
	
	/**
	 * function 1
	 * @param a_x_point area a.Lat
	 * @param a_y_point area a.lng
	 * @param b_x_point target b.lat
	 * @param b_y_point target b.lng
	 * @return scope
	 */
	public static double calDistance(Double a_x_point, Double a_y_point,Double b_x_point, Double b_y_point) {
		Double R = new Double(6371);
		Double dlat = (b_x_point - a_x_point) * Math.PI / 180;
		Double dlon = (b_y_point - a_y_point) * Math.PI / 180;
		Double aDouble = Math.sin(dlat / 2) * Math.sin(dlat / 2)
				       + Math.cos(a_x_point * Math.PI / 180)
				       * Math.cos(b_x_point * Math.PI / 180) * Math.sin(dlon / 2)
				       * Math.sin(dlon / 2);
		Double cDouble = 2 * Math.atan2(Math.sqrt(aDouble),Math.sqrt(1 - aDouble));
		double d = Math.round((R * cDouble) * 1000) ;//單位米
		
		return d;
	}
	
	/**
	 * function 2
	 * @param n1 area Lat
	 * @param e1 area lng
	 * @param n2 target lat
	 * @param e2 target lng
	 * @return scope
	 */
	public static int distance(double n1, double e1, double n2, double e2) {
		double jl_jd = 102834.74258026089786013677476285;//每经度单位米
		double jl_wd = 111712.69150641055729984301412873;//每纬度单位米
		double b = Math.abs((e1 - e2) * jl_jd);
		double a = Math.abs((n1 - n2) * jl_wd);
		return (int)Math.sqrt((a * a + b * b));//單位米
	}
	/**
	 * <pre>用來檢測  后一個X,Y座標 是否在前一個X,Y座標 areaScope範圍之內 </pre>
	 * @param areaLat
	 * @param areaLng
	 * @param areaScope
	 * @param lat
	 * @param lng
	 * @return
	 */
	public static boolean isScope(double areaLat,double areaLng,int areaScope, double lat, double lng){
		 
		int scope=distance(areaLat, areaLng, lat, lng);
		    
		return areaScope>=scope;
	}
	
	public static boolean isScopeForUser(String user,String other,double areaLat,double areaLng,int areaScope, double lat, double lng,int precision){
		 
		if(precision==0){
			precision=1000;
		}
		
		
		Log log =LogFactory.getLog("LAT_LNG_LOG");
		
		int scope=distance(areaLat, areaLng, lat, lng);
		
		log.info("-----------------start-----------------------");
		
	    log.info(" user :" +user +" lat :"+areaLat+" lng :"+areaLng);

		
	    log.info(" user :" +other +" lat :"+lat+" lng :"+lng);
	    log.info("容错率："+precision+"米");
		log.info("两者相距 :"+scope+"米");	
		log.info("允许误差："+(precision+areaScope)+"米");
		
		log.info("-------------------end------------------------");
		return areaScope+precision>=scope;
		//return true;
	}
	
	public static void main(String aaa[]){
		System.out.println("aaa="+calDistance(39.9,116.3, 31.2,121.4));
	}
}
